package com.rickpan.service;

import com.rickpan.entity.PaymentOrder;
import com.rickpan.entity.User;
import com.rickpan.entity.VipSubscription;
import com.rickpan.exception.BusinessException;
import com.rickpan.repository.PaymentOrderRepository;
import com.rickpan.repository.UserRepository;
import com.rickpan.repository.VipSubscriptionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * VIP订阅管理服务
 */
@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class VipSubscriptionService {

    private final VipSubscriptionRepository subscriptionRepository;
    private final UserRepository userRepository;
    private final PaymentOrderRepository paymentOrderRepository;

    /**
     * 创建VIP订阅 - 支付成功后调用
     */
    public VipSubscription createSubscription(Long userId, PaymentOrder.PlanType planType, Long orderId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new BusinessException("用户不存在"));

        PaymentOrder order = paymentOrderRepository.findById(orderId)
            .orElseThrow(() -> new BusinessException("支付订单不存在"));

        // 验证订单状态
        if (order.getStatus() != PaymentOrder.PaymentStatus.PAID) {
            throw new BusinessException("订单未支付，无法创建订阅");
        }

        // 计算订阅期限
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = calculateEndDate(startDate, planType);

        // 检查是否已有相同订单的订阅
        Optional<VipSubscription> existingSubscription = subscriptionRepository.findByOrderId(orderId);
        if (existingSubscription.isPresent()) {
            log.warn("订单 {} 已经创建过订阅，忽略重复创建", orderId);
            return existingSubscription.get();
        }

        // 创建订阅记录
        VipSubscription subscription = new VipSubscription();
        subscription.setUserId(userId);
        subscription.setOrderId(orderId);
        subscription.setPlanType(planType);
        subscription.setStartDate(startDate);
        subscription.setEndDate(endDate);
        subscription.setStatus(VipSubscription.SubscriptionStatus.ACTIVE);
        subscription.setOriginalAmount(order.getAmount());
        subscription.setActualAmount(order.getAmount());

        subscriptionRepository.save(subscription);

        // 更新用户VIP状态
        updateUserVipStatus(user, endDate);

        log.info("用户 {} 成功创建VIP订阅，计划类型: {}，到期时间: {}", 
                user.getUsername(), planType, endDate);

        return subscription;
    }

    /**
     * 续费VIP订阅
     */
    public VipSubscription renewSubscription(Long userId, PaymentOrder.PlanType planType, Long orderId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new BusinessException("用户不存在"));

        // 获取当前生效的订阅
        Optional<VipSubscription> currentSubscription = subscriptionRepository
            .findCurrentActiveSubscription(userId, LocalDate.now());

        LocalDate startDate;
        if (currentSubscription.isPresent() && currentSubscription.get().getEndDate().isAfter(LocalDate.now())) {
            // 从当前订阅结束时间开始续费
            startDate = currentSubscription.get().getEndDate().plusDays(1);
        } else {
            // 从今天开始
            startDate = LocalDate.now();
        }

        LocalDate endDate = calculateEndDate(startDate, planType);

        // 创建新的订阅记录
        VipSubscription newSubscription = new VipSubscription();
        newSubscription.setUserId(userId);
        newSubscription.setOrderId(orderId);
        newSubscription.setPlanType(planType);
        newSubscription.setStartDate(startDate);
        newSubscription.setEndDate(endDate);
        newSubscription.setStatus(VipSubscription.SubscriptionStatus.ACTIVE);

        PaymentOrder order = paymentOrderRepository.findById(orderId).orElse(null);
        if (order != null) {
            newSubscription.setOriginalAmount(order.getAmount());
            newSubscription.setActualAmount(order.getAmount());
        }

        subscriptionRepository.save(newSubscription);

        // 更新用户VIP状态
        updateUserVipStatus(user, endDate);

        log.info("用户 {} 成功续费VIP订阅，新的到期时间: {}", user.getUsername(), endDate);

        return newSubscription;
    }

    /**
     * 取消VIP订阅
     */
    public void cancelSubscription(Long userId, Long subscriptionId) {
        VipSubscription subscription = subscriptionRepository.findById(subscriptionId)
            .orElseThrow(() -> new BusinessException("订阅不存在"));

        if (!subscription.getUserId().equals(userId)) {
            throw new BusinessException("无权限操作此订阅");
        }

        if (subscription.getStatus() != VipSubscription.SubscriptionStatus.ACTIVE) {
            throw new BusinessException("订阅状态不允许取消");
        }

        // 更新订阅状态
        subscription.setStatus(VipSubscription.SubscriptionStatus.CANCELLED);
        subscriptionRepository.save(subscription);

        // 立即降级用户为BASIC
        User user = userRepository.findById(userId).orElse(null);
        if (user != null) {
            downgradeUserToBasic(user);
        }

        log.info("用户 {} 取消VIP订阅 {}", userId, subscriptionId);
    }

    /**
     * 获取用户的订阅列表
     */
    @Transactional(readOnly = true)
    public List<VipSubscription> getUserSubscriptions(Long userId) {
        return subscriptionRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }

    /**
     * 获取用户当前生效的订阅
     */
    @Transactional(readOnly = true)
    public Optional<VipSubscription> getCurrentActiveSubscription(Long userId) {
        return subscriptionRepository.findCurrentActiveSubscription(userId, LocalDate.now());
    }

    /**
     * 处理过期订阅
     */
    public void handleExpiredSubscriptions() {
        List<VipSubscription> expiredSubscriptions = subscriptionRepository
            .findExpiredActiveSubscriptions(LocalDate.now());

        for (VipSubscription subscription : expiredSubscriptions) {
            try {
                // 更新订阅状态为过期
                subscription.setStatus(VipSubscription.SubscriptionStatus.EXPIRED);
                subscriptionRepository.save(subscription);

                // 检查用户是否还有其他生效的订阅
                Optional<VipSubscription> activeSubscription = subscriptionRepository
                    .findCurrentActiveSubscription(subscription.getUserId(), LocalDate.now());

                if (activeSubscription.isEmpty()) {
                    // 没有其他生效订阅，降级为BASIC用户
                    User user = userRepository.findById(subscription.getUserId()).orElse(null);
                    if (user != null && user.getUserType() == User.UserType.VIP) {
                        downgradeUserToBasic(user);
                        log.info("用户 {} VIP订阅过期，已降级为BASIC用户", user.getUsername());
                    }
                }
            } catch (Exception e) {
                log.error("处理过期订阅失败: subscriptionId={}", subscription.getId(), e);
            }
        }

        if (!expiredSubscriptions.isEmpty()) {
            log.info("处理了 {} 个过期订阅", expiredSubscriptions.size());
        }
    }

    /**
     * 获取即将过期的订阅 (7天内)
     */
    @Transactional(readOnly = true)
    public List<VipSubscription> getExpiringSubscriptions() {
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = startDate.plusDays(7);
        return subscriptionRepository.findExpiringSubscriptions(startDate, endDate);
    }

    /**
     * 计算订阅结束日期
     */
    private LocalDate calculateEndDate(LocalDate startDate, PaymentOrder.PlanType planType) {
        return switch (planType) {
            case MONTHLY_VIP -> startDate.plusMonths(1);
            case YEARLY_VIP -> startDate.plusYears(1);
        };
    }

    /**
     * 更新用户VIP状态
     */
    private void updateUserVipStatus(User user, LocalDate endDate) {
        // 🔥 修复：保护管理员权限，只有非管理员用户才设置为VIP类型
        if (user.getUserType() != User.UserType.ADMIN) {
            user.setUserType(User.UserType.VIP);
        }
        user.setVipExpireTime(endDate.atTime(23, 59, 59));
        
        // 升级存储配额到100GB
        if (user.getStorageQuota() < 107374182400L) {
            user.setStorageQuota(107374182400L); // 100GB
        }
        
        userRepository.save(user);
        
        log.info("用户 {} VIP状态更新完成，用户类型: {}, VIP过期时间: {}", 
                user.getUsername(), user.getUserType(), user.getVipExpireTime());
    }

    /**
     * 降级用户为BASIC
     */
    private void downgradeUserToBasic(User user) {
        // 🔥 修复：保护管理员权限，只有非管理员用户才降级为BASIC
        if (user.getUserType() != User.UserType.ADMIN) {
            user.setUserType(User.UserType.BASIC);
        }
        user.setVipExpireTime(null);
        
        // 降级存储配额到5GB (但不删除已存储的文件)
        // 管理员保持较大的存储配额
        if (user.getUserType() != User.UserType.ADMIN) {
            user.setStorageQuota(5368709120L); // 5GB
        }
        
        userRepository.save(user);
        
        log.info("用户 {} VIP已过期，用户类型: {}, 存储配额: {}GB", 
                user.getUsername(), user.getUserType(), user.getStorageQuota() / (1024 * 1024 * 1024));
    }
}